import { Controller, Get, Post, Body, Patch, Param, Delete, Res, UploadedFile, UseInterceptors, HttpStatus, NotFoundException } from '@nestjs/common';
import { UploadService } from './upload.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { Response } from 'express';

@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) { }

  // 上传图片（images文件夹）
  @Post('images')
  @UseInterceptors(FileInterceptor('file'))
  uploadImage(@UploadedFile() file) {
    console.log('file', file);
    
    return { url: `/public/${file.filename}` };
  }
  @Post('images')
  @UseInterceptors(FileInterceptor('file'))
  uploadImage2(@UploadedFile() wangeditor_uploaded_image) {
    return { url: `/public/${wangeditor_uploaded_image
.filename}` };
  }

  // 获取图片文件内容（下载/预览）
  @Get('images/:filename')
  getImage(@Param('filename') filename: string, @Res() res: Response) {
    try {
      const file = this.uploadService.readFile(filename);
      res.setHeader('Content-Type', 'image/*');
      res.status(HttpStatus.OK).send(file);
    } catch (e) {
      throw new NotFoundException('文件不存在');
    }
  }

  // 查找图片是否存在
  @Get('images/exists/:filename')
  exists(@Param('filename') filename: string) {
    return { exists: this.uploadService.findFile(filename) };
  }

  // 删除图片
  @Delete('images/:filename')
  delete(@Param('filename') filename: string) {
    this.uploadService.deleteFile(filename);
    return { message: '删除成功' };
  }

  // 更新/覆盖图片
  @Post('images/update/:filename')
  @UseInterceptors(FileInterceptor('file', {
    dest: 'src/images',
  }))
  updateImage(@Param('filename') filename: string, @UploadedFile() file) {
    this.uploadService.updateFile(filename, file.buffer);
    return { message: '更新成功', url: `/upload/images/${filename}` };
  }

  // 列出所有图片文件名
  @Get('images')
  list() {
    return this.uploadService.listFiles();
  }
}
